<!--
 * @Author: ZhaoZhiqi
 * @Date: 2024-05-09 17:31:21
 * @LastEditors: ZhaoZhiqi
 * @LastEditTime: 2024-05-10 11:54:44
 * @Description: 签名板组件
 * @FilePath: \parking-mini\src\components\Signature.vue
-->
<template>
    <view v-show="visible" class="signature-container">
        <!-- 自定义导航栏 -->
        <NaviBar title="签署" :autoBack="true" />
        <view class="wrapper">
            <view class="handBtn">
                <button @click="retDraw" class="delBtn">清除</button>
                <button @click="close" class="saveBtn">取消</button>
                <button @click="subCanvas" class="subBtn">确认</button>
            </view>
            <view class="handCenter">
                <canvas class="handWriting" :disable-scroll="true" @touchstart="uploadScaleStart" @touchmove="uploadScaleMove" canvas-id="handWriting" />
                <!--用于旋转图片的canvas容器-->
                <canvas style="position: absolute; bottom: -10000rpx" :style="{ width: cavWidth, height: cavWidth1 }" canvas-id="handWriting2"></canvas>
            </view>
        </view>
    </view>
</template>

<script>
import { baseUrl } from "../api/baseUrl";

export default {
    name: "Signature",
    props: {
        visible: {
            type: Boolean,
            default: true,
        },
    },
    data() {
        return {
            canvasName: "handWriting",
            ctx: "",
            startX: null,
            startY: null,
            canvasWidth: 0,
            canvasHeight: 0,
            selectColor: "black",
            lineColor: "#1A1A1A", // 颜色
            canvas: null,
            cavWidth: 2000,
            cavWidth1: 2000,
            lineSize: 5, // 笔记倍数
        };
    },
    created() {
        this.ctx = uni.createCanvasContext("handWriting", this);
        this.$nextTick(() => {
            uni.createSelectorQuery()
                .in(this)
                .select(".handCenter")
                .boundingClientRect((rect) => {
                    this.canvasWidth = rect.width;
                    this.canvasHeight = rect.height;
                    /* 将canvas背景设置为 白底，不设置  导出的canvas的背景为透明 */
                    this.setCanvasBg("#fff");
                })
                .exec();
        });
    },
    methods: {
        // 笔迹开始
        uploadScaleStart(e) {
            this.startX = e.changedTouches[0].x;
            this.startY = e.changedTouches[0].y;
            //设置画笔参数
            //画笔颜色
            this.ctx.setStrokeStyle(this.lineColor);
            //设置线条粗细
            this.ctx.setLineWidth(this.lineSize);
            //设置线条的结束端点样式
            this.ctx.setLineCap("round"); //'butt'、'round'、'square'
            //开始画笔
            this.ctx.beginPath();
        },
        // 笔迹移动
        uploadScaleMove(e) {
            //取点
            let temX = e.changedTouches[0].x;
            let temY = e.changedTouches[0].y;
            //画线条
            this.ctx.moveTo(this.startX, this.startY);
            this.ctx.lineTo(temX, temY);
            this.ctx.stroke();
            this.startX = temX;
            this.startY = temY;
            this.ctx.draw(true);
        },
        /**
         * 重写
         */
        retDraw() {
            this.ctx.clearRect(0, 0, 700, 730);
            this.ctx.draw();
            //设置canvas背景
            this.setCanvasBg("#fff");
        },
        /**
         * @param {Object} str
         * @param {Object} color
         * 选择颜色
         */
        selectColorEvent(str, color) {
            this.selectColor = str;
            this.lineColor = color;
        },
        // 确认
        subCanvas() {
            const _this = this;
            uni.canvasToTempFilePath(
                {
                    canvasId: "handWriting",
                    fileType: "png",
                    quality: 1, //图片质量
                    success(res) {
                        console.log(res.tempFilePath, "canvas生成图片地址");
                        wx.getImageInfo({
                            // 获取图片的信息
                            src: res.tempFilePath,
                            success: (res1) => {
                                // 将canvas1的内容复制到canvas2中
                                let canvasContext = wx.createCanvasContext("handWriting2", _this);
                                let rate = res1.height / res1.width;
                                let width = 300 / rate;
                                let height = 300;
                                _this.cavWidth = 300 / rate;
                                _this.cavWidth1 = 300;
                                canvasContext.translate(height / 2, width / 2);
                                canvasContext.rotate((270 * Math.PI) / 180);
                                canvasContext.drawImage(res.tempFilePath, -width / 2, -height / 2, width, height);
                                canvasContext.draw(false, () => {
                                    // 将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中
                                    wx.canvasToTempFilePath(
                                        {
                                            // 把当前画布指定区域的内容导出生成指定大小的图片。在 draw() 回调里调用该方法才能保证图片导出成功。
                                            canvasId: "handWriting2",
                                            fileType: "png",
                                            quality: 1, //图片质量
                                            success(res2) {
                                                wx.uploadFile({
                                                    url: `${baseUrl()}/app/file/upload`,
                                                    filePath: res2.tempFilePath,
                                                    name: "file",
                                                    success(res3) {
                                                        console.log(res3);
                                                        if (res3.statusCode !== 200 ) {
                                                            wx.showToast({
                                                                title: "上传签名错误",
                                                                icon: "none",
                                                            });
                                                            return false;
                                                        }
                                                        let data = JSON.parse(res3.data);
                                                        if (data.code !== 200) {
                                                            wx.showToast({
                                                                title: "上传签名接口错误",
                                                                icon: "none",
                                                            });
                                                            return false;
                                                        }
                                                        let url = baseUrl() + data.data;
                                                        _this.retDraw();
                                                        _this.$emit("success", url);
                                                    },
                                                    fail(err) {
                                                        console.log(err);
                                                        wx.showToast({
                                                            title: "uploadFile错误",
                                                            icon: "none",
                                                        });
                                                    },
                                                });
                                            },
                                            fail: (err) => {
                                                console.log(err);
                                            },
                                            complete: (res) => {
                                                console.log("canvasToTempFilePath2 complete", res);
                                            },
                                        },
                                        _this
                                    );
                                });
                            },
                            fail: (err) => {
                                console.log(err);
                            },
                            complete: (res) => {
                                console.log("getImageInfo complete", res);
                            },
                        });
                    },
                    fail: (err) => {
                        console.log(err);
                    },
                },
                this
            );
        },
        //旋转图片，生成新canvas实例
        rotate(cb) {
            const that = this;
            wx.createSelectorQuery()
                .select("#handWriting2")
                .fields({
                    node: true,
                    size: true,
                })
                .exec((res) => {
                    const rotateCanvas = res[0].node;
                    const rotateCtx = rotateCanvas.getContext("2d");
                    //this.ctxW-->所绘制canvas的width
                    //this.ctxH -->所绘制canvas的height
                    rotateCanvas.width = this.ctxH;
                    rotateCanvas.height = this.ctxW;
                    wx.canvasToTempFilePath({
                        canvas: that.canvas,
                        success(res) {
                            const img = rotateCanvas.createImage();
                            img.src = res.tempFilePath;
                            img.onload = function () {
                                rotateCtx.translate(rotateCanvas.width / 2, rotateCanvas.height / 2);
                                rotateCtx.rotate((270 * Math.PI) / 180);
                                rotateCtx.drawImage(img, -rotateCanvas.height / 2, -rotateCanvas.width / 2);
                                rotateCtx.scale(that.pixelRatio, that.pixelRatio);
                                cb(rotateCanvas);
                            };
                        },
                        fail(err) {
                            console.log(err);
                        },
                    });
                });
        },
        //取消
        close() {
            this.retDraw();
            this.$emit("close", false);
        },
        //设置canvas背景色  不设置  导出的canvas的背景为透明
        //@params：字符串  color
        setCanvasBg(color) {
            /* 将canvas背景设置为 白底，不设置  导出的canvas的背景为透明 */
            //rect() 参数说明  矩形路径左上角的横坐标，左上角的纵坐标, 矩形路径的宽度, 矩形路径的高度
            //这里是 canvasHeight - 4 是因为下边盖住边框了，所以手动减了写
            this.ctx.rect(0, 0, this.canvasWidth, this.canvasHeight - 4);
            // ctx.setFillStyle('red')
            this.ctx.setFillStyle(color);
            this.ctx.fill(); //设置填充
            this.ctx.draw(); //开画
        },
        toJSON() {},
    },
};
</script>

<style scoped>
.signature-container {
    width: 100%;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 2000;
}

.wrapper {
    position: relative;
    width: 100%;
    height: 100vh;
    overflow: auto;
    display: flex;
    align-content: center;
    flex-direction: row;
    justify-content: center;
    font-size: 28rpx;
}

.handWriting {
    background: #fff;
    width: 100%;
    height: 100vh;
}

.handCenter {
    position: relative;
    border-left: 2rpx solid #e9e9e9;
    flex: 5;
    overflow: hidden;
    box-sizing: border-box;
}

.handBtn button {
    font-size: 28rpx;
}

.handBtn {
    height: 100vh;
    display: inline-flex;
    flex-direction: column;
    justify-content: space-between;
    align-content: space-between;
    flex: 1;
    background-color: #fff;
}

.delBtn {
    width: 200rpx;
    position: absolute;
    bottom: 350rpx;
    left: -35rpx;
    transform: rotate(90deg);
    color: #666;
}

.subBtn {
    width: 200rpx;
    position: absolute;
    bottom: 52rpx;
    left: -35rpx;
    display: inline-flex;
    transform: rotate(90deg);
    background: #29cea0;
    color: #fff;
    margin-bottom: 60rpx;
    text-align: center;
    justify-content: center;
}

/*Peach - 新增 - 保存*/

.saveBtn {
    width: 200rpx;
    position: absolute;
    bottom: 590rpx;
    left: -35rpx;
    transform: rotate(90deg);
    color: #666;
}
</style>
